package _08_动态规划;
/*
    最长公共子序列
 */
public class LSC {
    public static void main(String[] args) {
        System.out.println(longestCommonSubsequence("abcde","ace"));
        System.out.println(longestCommonSubsequence("abc","abc"));
        System.out.println(longestCommonSubsequence("abc","def"));
    }

    //dp
    static int lsc(String text1,String text2){
        if(text1 == null || text1.length() == 0) return 0;
        if(text2 == null || text2.length() == 0) return 0;
        char[] char1 = text1.toCharArray();
        char[] char2 = text2.toCharArray();
        //dp(i,j):是char1前i个元素和char2前j个元素的最长公共子序列的长度
        //dp[i][0],dp[0][j]都为0
        int[][] dp = new int[char1.length+1][char2.length+1];
        for(int i=1;i<=char1.length;++i){
            for(int j=1;j<=char2.length;++j){
                if(char1[i-1]==char2[j-1]){ //最后一个元素相等
                    dp[i][j] = dp[i-1][j-1]+1;
                }else{
                    dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]);
                }
            }
        }

        return dp[char1.length][char2.length];

    }


    static int longestCommonSubsequence(String text1,String text2){
        if(text1 == null || text1.length() == 0) return 0;
        if(text2 == null || text2.length() == 0) return 0;
        char[] char1 = text1.toCharArray();
        char[] char2 = text2.toCharArray();

        return longestCommonSubsequence(char1,char1.length,char2, char2.length);
     }

    //递归写法
    static int longestCommonSubsequence(char[] char1,int i,char[] char2,int j){
        if(i == 0 || j == 0) return 0;
        if(char1[i-1] != char2[j-1]){
            return Math.max(longestCommonSubsequence(char1,i-1,char2,j),
                    longestCommonSubsequence(char1,i,char2,j-1));
        }
        return longestCommonSubsequence(char1,i-1,char2,j-1) + 1;
    }
}
